<script setup name="staff_list">

import OAMain from "@/components/OAMain.vue";
import {onMounted, reactive, ref, watch} from "vue";
import datetimeFormat from "@/utils/datetimeFormat.js";
import staffhttp from "@/api/staffhttp.js";
import {ElMessage} from "element-plus";
import OADialog from "@/components/OADialog.vue";
import {useAuthStore} from "@/stores/auth.js";
let pagination = reactive({
  page: 1,
  total: 0,
})
let staffs = ref([])
let page_size = ref(10)
let dialogVisible = ref(false)
let staffForm = reactive({
  status: 1,
  telephone: 1
})
let departments = ref([])
let filterForm = reactive({
  department_id:null,
  realname:"",
  date_joined:[]
})
const base_url = import.meta.env.VITE_API_URL;
let handleIndex = 0
let tableRef = ref()
async function fetchStaffs(page, page_size) {
  try {
    // 获取员工列表
    let result = await staffhttp.listStaff(page, page_size, filterForm)
    result = result.data
    pagination.total = result.count
    pagination.page = page
    staffs.value = result.results
  } catch (error) {
    ElMessage.error(error)
  }
}
onMounted( async()=>{
  fetchStaffs(1, page_size.value)
  try{
     let data = await staffhttp.getAllDepartments()
    departments.value = data.data.results
  }catch(error){
    ElMessage.error(error)
  }
})
watch(()=>pagination.page, async function (value) {
   await fetchStaffs(value, page_size.value)
})
const tableKey = ref(0);
watch(staffs, () => {
  tableKey.value++;
});
watch(page_size, function (value) {
  if(pagination.page === 1) {
    fetchStaffs(1, value)
  }else{
    pagination.page = 1;
  }
})

const onEditStaff = (index) => {
  handleIndex = index;
  dialogVisible.value = true
  let staff = staffs.value[index]
  staffForm.status = staff.status
  staffForm.telephone = staff.telephone
}
const onSubmitEditStaff = async () => {
  let staff = staffs.value[handleIndex]
  try {
    let newStaff = await staffhttp.updateStaff(staff.uid, staffForm)
    ElMessage.success(staff.realname + "信息修改 成功")
    dialogVisible.value = false
    staffs.value.splice(handleIndex, 1, newStaff)
  }catch(error){
    ElMessage.error(error)
  }
}
const onSearch = () => {
  fetchStaffs(1, page_size.value)
}
const onDownload = async () => {
  let rows = tableRef.value.getSelectionRows()
  if (!rows.length || rows[0].length === 0) {
    ElMessage.error("请选择需要下载的员工")
    return;
  }
  try {
    let response = await staffhttp.downloadStaff(rows.map(row => row.uid))
    let href = URL.createObjectURL(response.data)
    const a = document.createElement("a");
    a.href = href;
    a.setAttribute("download", '员工信息.xlsx');
    document.body.appendChild(a);
    a.click()
    document.body.removeChild(a);
    URL.revokeObjectURL(href)
    ElMessage.success("员工信息下载成功")
  }catch(error){
    ElMessage.error(error)
  }
}
const onUploadSuccess = () => {
  ElMessage.success("员工上传成功")
  fetchStaffs(1, page_size.value)
}
const onUploadError = (error) => {
  const message = JSON.parse(error.message).detail
  ElMessage.error("员工上传失败！" + message)
  fetchStaffs(1, page_size.value)
}
</script>

<template>
<OAMain title="员工列表">
  <el-card>
    <el-form :inline="true" >
      <el-form-item label="按部门" class="my-form-inline">
        <el-select v-model="filterForm.department_id">
          <el-option v-for="department in departments" :label="department.name" :value="department.id"
                     :key="department.name" />
        </el-select>
      </el-form-item>
      <el-form-item label="按姓名" class="">
        <el-input type="text" v-model="filterForm.realname" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="按入职时间" class="">
          <el-date-picker v-model='filterForm.date_joined' type="daterange" :value='filterForm.date_joined' start-placeholder="起始时间"
                          end-placeholder="结束时间" format="YYYY-MM-DD" value-format="yyyy-MM-dd"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="onSearch">查找</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Download" @click="onDownload">下载</el-button>
      </el-form-item>
      <el-form-item>
        <el-upload
            :action="base_url+'/staff/upload/'"
            :on-success="onUploadSuccess"
            :headers="{Authorization: 'JWT ' + useAuthStore().token}"
            :on-error="onUploadError"
            :show-file-list="false"
            :auto-upload="true"
            accept=".xlsx, .xls"
        >
          <el-button type="danger" icon="upload">上传</el-button>

        </el-upload>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card>
    <el-table :data="staffs" :key="tableKey" ref="tableRef">
      <el-table-column  type="selection" width="55"></el-table-column>
      <el-table-column label="序号" >
        <template #default="scope">{{scope.$index + 1}}</template>
      </el-table-column>
      <el-table-column  prop="realname" label="姓名"/>
      <el-table-column prop="department.name" label="部门"  />
      <el-table-column label="入职时间" width="140" >
        <template #default="scope">{{datetimeFormat.stringFromDate(scope.row.date_joined)}}</template>
      </el-table-column>
      <el-table-column prop="email" label="员工邮箱" />
      <el-table-column prop="telephone" label="手机号"/>
      <el-table-column label="状态">
        <template #default="scope">
          <el-tag v-if="scope.row.status == 1" type="success">正常</el-tag>
          <el-tag v-else-if="scope.row.status == 2" type="warning">未激活</el-tag>
          <el-tag v-else type="danger">已锁定</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" icon="Edit" circle @click="onEditStaff(scope.$index)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <div style="display: flex; justify-content: space-between;">
        <el-form-item label="每页：">
          <el-select v-model="page_size" size="small" style="width: 100px;">
            <el-option select label="10条/页" :value="10" />
            <el-option label="20条/页" :value="20" />
          </el-select>
        </el-form-item>
        <el-pagination background layout="prev, pager, next" :total="pagination.total"
                       v-model:current-page="pagination.page" :page-size="page_size" />
      </div>
    </template>
  </el-card>
</OAMain>

  <OADialog title="修改员工状态" v-model="dialogVisible" @submit="onSubmitEditStaff">
    <el-form :model="staffForm" label-position="left">
      <el-form-item label="手机号">
        <el-input type="text" v-model="staffForm.telephone"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="staffForm.status">
          <el-radio :value="1" size="small">激活</el-radio>
          <el-radio :value="3" size="small">锁定</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

  </OADialog>
</template>

<style scoped>
.my-form-inline .el-input {
  --el-input-width: 140px;
}

.my-form-inline .el-select {
  --el-select-width: 140px;
}

.el-form--inline .el-form-item {
  margin-right: 20px;
}
</style>